//package org.example.common.async.executor;
//
//import org.example.common.async.callback.DefaultGroupCallback;
//import org.example.common.async.callback.IGroupCallback;
//import org.example.common.async.wrapper.WorkerWrapper;
//import org.example.common.threadpool.ThreadPoolConfig;
//import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
//
//import java.time.Duration;
//import java.util.*;
//import java.util.concurrent.*;
//import java.util.stream.Collectors;
//
///**
// * 类入口，可以根据自己情况调整core线程的数量
// *
// * @author wuweifeng
// * @version 1.0
// * @since 2019-12-18
// */
//@SuppressWarnings({"unchecked", "raw"})
//public class Async {
//    /**
//     * 默认不定长线程池
//     */
//    private static final ExecutorService COMMON_POOL = createThreadPool();
//    /**
//     * 注意，这里是个static，也就是只能有一个线程池。用户自定义线程池时，也只能定义一个
//     */
//    private static ExecutorService executorService;
//
//    private static ExecutorService createThreadPool() {
//        TaskExecutionProperties properties = new TaskExecutionProperties();
//        TaskExecutionProperties.Pool pool = properties.getPool();
//        pool.setCoreSize(10);
//        pool.setMaxSize(10);
//        pool.setKeepAlive(Duration.ofSeconds(60));
//        pool.setAllowCoreThreadTimeout(true);
//        pool.setQueueCapacity(200);
//        TaskExecutionProperties.Shutdown shutdown = properties.getShutdown();
//        shutdown.setAwaitTermination(true);
//        shutdown.setAwaitTerminationPeriod(Duration.ofSeconds(0));
//        properties.setThreadNamePrefix("Async-Tool-");
//        return ThreadPoolConfig.createThreadPool(properties, new ThreadPoolExecutor.CallerRunsPolicy());
//    }
//
//    /**
//     * 出发点
//     */
//    public static boolean beginWork(long timeout, ExecutorService executorService, List<WorkerWrapper> workerWrappers) throws ExecutionException, InterruptedException {
//        if (workerWrappers == null || workerWrappers.isEmpty()) {
//            return false;
//        }
//        //保存线程池变量
//        Async.executorService = executorService;
//        //定义一个map，存放所有的wrapper，key为wrapper的唯一id，value是该wrapper，可以从value中获取wrapper的result
//        Map<String, WorkerWrapper> forParamUseWrappers = new ConcurrentHashMap<>();
//        CompletableFuture[] futures = new CompletableFuture[workerWrappers.size()];
//        for (int i = 0; i < workerWrappers.size(); i++) {
//            WorkerWrapper wrapper = workerWrappers.get(i);
//            futures[i] = CompletableFuture.runAsync(() -> wrapper.work(executorService, timeout, forParamUseWrappers), executorService);
//        }
//        try {
//            CompletableFuture.allOf(futures).get(timeout, TimeUnit.MILLISECONDS);
//            return true;
//        } catch (TimeoutException e) {
//            Set<WorkerWrapper> set = new HashSet<>();
//            totalWorkers(workerWrappers, set);
//            for (WorkerWrapper wrapper : set) {
//                wrapper.stopNow();
//            }
//            return false;
//        }
//    }
//
//    /**
//     * 如果想自定义线程池，请传pool。不自定义的话，就走默认的COMMON_POOL
//     */
//    public static boolean beginWork(long timeout, ExecutorService executorService, WorkerWrapper... workerWrapper) throws ExecutionException, InterruptedException {
//        if (workerWrapper == null || workerWrapper.length == 0) {
//            return false;
//        }
//        List<WorkerWrapper> workerWrappers = Arrays.stream(workerWrapper).collect(Collectors.toList());
//        return beginWork(timeout, executorService, workerWrappers);
//    }
//
//    /**
//     * 同步阻塞,直到所有都完成,或失败
//     */
//    public static boolean beginWork(long timeout, WorkerWrapper... workerWrapper) throws ExecutionException, InterruptedException {
//        return beginWork(timeout, COMMON_POOL, workerWrapper);
//    }
//
//    public static void beginWorkAsync(long timeout, IGroupCallback groupCallback, WorkerWrapper... workerWrapper) {
//        beginWorkAsync(timeout, COMMON_POOL, groupCallback, workerWrapper);
//    }
//
//    /**
//     * 异步执行,直到所有都完成,或失败后，发起回调
//     */
//    public static void beginWorkAsync(long timeout, ExecutorService executorService, IGroupCallback groupCallback, WorkerWrapper... workerWrapper) {
//        if (groupCallback == null) {
//            groupCallback = new DefaultGroupCallback();
//        }
//        IGroupCallback finalGroupCallback = groupCallback;
//        if (executorService != null) {
//            executorService.submit(() -> {
//                try {
//                    boolean success = beginWork(timeout, executorService, workerWrapper);
//                    if (success) {
//                        finalGroupCallback.success(Arrays.asList(workerWrapper));
//                    } else {
//                        finalGroupCallback.failure(Arrays.asList(workerWrapper), new TimeoutException());
//                    }
//                } catch (ExecutionException | InterruptedException e) {
//                    finalGroupCallback.failure(Arrays.asList(workerWrapper), e);
//                    Thread.currentThread().interrupt();
//                }
//            });
//        } else {
//            COMMON_POOL.submit(() -> {
//                try {
//                    boolean success = beginWork(timeout, COMMON_POOL, workerWrapper);
//                    if (success) {
//                        finalGroupCallback.success(Arrays.asList(workerWrapper));
//                    } else {
//                        finalGroupCallback.failure(Arrays.asList(workerWrapper), new TimeoutException());
//                    }
//                } catch (ExecutionException | InterruptedException e) {
//                    finalGroupCallback.failure(Arrays.asList(workerWrapper), e);
//                    Thread.currentThread().interrupt();
//                }
//            });
//        }
//
//    }
//
//    /**
//     * 总共多少个执行单元
//     */
//    @SuppressWarnings("unchecked")
//    private static void totalWorkers(List<WorkerWrapper> workerWrappers, Set<WorkerWrapper> set) {
//        set.addAll(workerWrappers);
//        for (WorkerWrapper wrapper : workerWrappers) {
//            if (wrapper.getNextWrappers() == null) {
//                continue;
//            }
//            List<WorkerWrapper> wrappers = wrapper.getNextWrappers();
//            totalWorkers(wrappers, set);
//        }
//
//    }
//
//    /**
//     * 关闭线程池
//     */
//    public static void shutDown() {
//        shutDown(executorService);
//    }
//
//    /**
//     * 关闭线程池
//     */
//    public static void shutDown(ExecutorService executorService) {
//        if (executorService != null) {
//            executorService.shutdown();
//        } else {
//            COMMON_POOL.shutdown();
//        }
//    }
//
//    public static String getThreadCount() {
//        return "TODO";
//    }
//}
